package com.tczs.dispatch;

import com.alibaba.fastjson.JSONObject;
import com.tczs.web.config.MessageEnZhData;
import com.tczs.server.request.ServerRequestModel;
import com.tczs.dispatch.response.ResponseResult;
import com.tczs.dispatch.response.ResponseType;
import com.tczs.dispatch.response.StreamResponse;
import org.apache.log4j.Logger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;

public class DispatchRequest {
    private static Logger logger = Logger.getLogger(DispatchRequest.class);

    public static ResponseResult dispatch(ServerRequestModel request,Handler handler){
        ResponseResult result = new ResponseResult();
        Object obj = CollectAction.objects.get(handler.getClazz());
        Parameter[] parameters = handler.getParameters();
        Object[] objects = new Object[parameters.length];
        objects[0] = request.getMethod();
        for(int i=1,length=parameters.length;i<length;i++){
            objects[i] = request.getParams().get(parameters[i].getName());
        }
        try {
            Object value = handler.getMethod().invoke(obj, objects);
            result.setCode(200);
            if(value instanceof com.alibaba.fastjson.JSONObject){
                result.setType(ResponseType.JSON);
                result.setValue((JSONObject)value);
            }else if(handler.getMethod().getAnnotation(StreamResponse.class) != null){
                result.setType(ResponseType.STREAM);
                result.setFilePath((String)value);
            }else if(value instanceof java.lang.String){
                result.setType(ResponseType.FILE);
                result.setFilePath((String)value);
            }else {
                logger.error(value);
                throw new IllegalStateException();
            }
            logger.info("response result: "+value);
            return result;
        }catch (InvocationTargetException e){
            Throwable targetException = e.getTargetException();
            if(targetException.getClass() == CustomerException.class){
                result.setCode(555);
                result.setErrorMessage(targetException.getMessage());
                return result;
            }
            logger.error("the currency system is busy",e);
            result.setCode(500);
            return result;
        }catch (IllegalStateException e){
            logger.error("response type is error",e);
            result.setCode(500);
            return result;
        }catch (Exception e) {
            logger.error("the currency system is busy",e);
           result.setCode(500);
           return result;
        }
    }

}
